import { deleteWorkplacesDataApi, getWorkplacesApi } from "@/api/workplace";
import MyCard from "@/components/card"
import { ExclamationCircleFilled, PlusOutlined } from '@ant-design/icons';
import { App, Button, Input, Space, Table } from "antd"
import type { SearchProps } from "antd/es/input";

import type { TableProps } from "antd/lib";
import { useEffect, useRef, useState } from "react";
import WorkplaceForm, { type WorkplaceRef } from "./WorkplaceForm";
interface DataType {
  _id: string;
  name: string;
  country: string;
  city: string[];
  address: string;
  desc: string;
  organizationTypeId: string;
  postcode: string;
}


const fixedColumns: TableProps<DataType>['columns'] = [

  {
    title: '工作地点名称',
    dataIndex: 'name',
  },
  {
    title: '国家/地区',
    dataIndex: 'country'
  },
  {
    title: '所在城市',
    dataIndex: 'city',
    render: (item) => {
      return <span>{item.join('>')}</span>
    }
  },
  {
    title: '详细地址',
    dataIndex: 'address',
    ellipsis: true,
  },
  {
    title: '邮政编码',
    dataIndex: 'postcode'
  },
  {
    title: '类型',
    dataIndex: ['organizationTypeId', 'name']

  },
  {
    title: '员工数量',

  },
  {
    title: '描述',
    dataIndex: 'desc',
    ellipsis: true,
  },

];



const Workplace = () => {

  const [searchData, setSearchData] = useState({ searchValue: '' });
  const [workplaceData, setWorkPlaceData] = useState<{ rows: DataType[], total: number }>({ rows: [], total: 0 });
  const formRef = useRef<WorkplaceRef>(null);
  const { message, modal } = App.useApp();
  const choseCheckBoxData = useRef<React.Key[]>([]);
  const [pageData, setPageData] = useState({ currentPage: 1, pageSize: 10 })

  useEffect(() => {
    getWorkplaces();
  }, [pageData, searchData]);



  //表单额外列配置
  const columns: TableProps<DataType>['columns'] = [
    ...fixedColumns, {
      title: '操作',
      key: 'action',
      width: 120,
      render: (item) => (
        <Space size="middle">
          <a onClick={() => {
            formRef.current!.onOpenForm(item);
          }
          }>编辑</a>
          <a onClick={() => {
            showConfirm(item._id)
          }}>删除</a>
        </Space>
      ),
    },

  ];

  //删除按钮
  const showConfirm = (_id: string) => {
    modal.confirm({
      title: '删除确认',
      icon: <ExclamationCircleFilled />,
      content: '职务删除后无法恢复，确定要删除吗？',
      onOk() {
        deleteWorkplacesData(_id);
        getWorkplaces();
      },
      onCancel() {
      },
    });
  };


  //删除
  const deleteWorkplacesData = async (_id: string) => {
    const res = await deleteWorkplacesDataApi({ _id });
    if (res.code == 200) {
      message.success('删除成功')
    } else {
      message.error(res.message)
    }
  }

  //搜索框
  const onSearch: SearchProps['onSearch'] = (value) => {
    setSearchData({ searchValue: value })
  };

  //获取工作地点
  const getWorkplaces = () => {
    getWorkplacesApi({
      ...searchData,
      ...pageData,
    }).then(res => {
      if (res.code == 200) {
        setWorkPlaceData(res.data);
      }
    })
  }
  //多选框
  const onChoseCheckBox = (selectedRowKeys: any) => {
    choseCheckBoxData.current = selectedRowKeys
  }
  //批量删除
  const deleteCheckBoxWorkplacesData = () => {
    if (choseCheckBoxData.current.length > 0) {
      modal.confirm({
        title: '删除确认',
        icon: <ExclamationCircleFilled />,
        content: '职务删除后无法恢复，确定要删除吗？',
        onOk() {
          deleteWorkplacesDataApi({ _id: choseCheckBoxData.current }).then(res => {
            if (res.code == 200) {
              message.success('删除成功');
              getWorkplaces();
            } else {
              message.error(res.message);
            }
          })
          getWorkplaces();
        },
        onCancel() {
        },
      });
    } else {
      message.warning('请先勾选需要删除的数据');
    }

  }
  //分页
  const changePageData = (currentPage: number, pageSize: number) => {
    setPageData({ currentPage, pageSize })
  }

  return (
    <>
      <MyCard title='工作地点'>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20 }}>
          <Input.Search placeholder="请输入关键字" style={{ width: 300 }} allowClear onSearch={onSearch} />
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => {
              formRef.current!.onOpenForm();
            }}>新增工作地点</Button>
            <Button color="primary" variant="outlined" onClick={deleteCheckBoxWorkplacesData}>批量删除</Button>
          </Space>
        </div>
        <Table<DataType> columns={columns} dataSource={workplaceData.rows} rowKey="_id" rowSelection={{ onChange: onChoseCheckBox }}
          pagination={{
            total: workplaceData.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `总计 ${total} 条数据`,
            pageSizeOptions: [5, 10, 20, 50],
            onChange: changePageData
          }} />
      </MyCard>
      <WorkplaceForm ref={formRef} getWorkplaces={getWorkplaces} />

    </>
  )
}

export default Workplace